import { queryPage, queryInfoById, create, update, queryProblemPage, queryProblemList } from './service';
import { queryDictList } from '@/services/dict';
import { routerRedux } from 'dva/router';
import { DICT } from './enum';

export default {
  namespace: 'report_template',

  state: {
    list: { data: [] },
    details: [],
    cond: {},
    dict: {}
  },

  effects: {
    *initCond(_, { put }) {
      yield put({ type: 'setCond', payload: { type: '2' } });
      yield put({ type: 'queryPage' })
    },
    *updateCond({ payload = { pageNum: 1, pageSize: 10 } }, { put }) {
      const { pageSize, pageNum, ...cond } = payload;
      yield put({ type: 'setCond', payload: cond });
      yield put({ type: 'queryPage', payload });
      yield put({ type: 'queryProblemPage', payload });
    },
    *queryPage({ payload = { pageNum: 1, pageSize: 10 } }, { call, put, select }) {
      const cond = yield select(state => state.report_template.cond);
      const params = { ...payload, ...cond };
      const { list = [], total } = yield call(queryPage, params);
      yield put({ type: 'queryDict', payload: {keyList: DICT} });
      yield put({ type: 'setPage', payload: { list, total } })
    },
    *queryDict({ payload }, { call, put }) {
      const dict = yield call(queryDictList, payload);
      yield put({ type: 'setDict', payload: dict })
    },
    *queryInfoById({ payload }, { call, put }) {
      const response = yield call(queryInfoById, payload);
      yield put({ type: 'setInfo', payload: response })
    },
    *create({ payload }, { call, put }) {
      yield call(create, payload);
      yield put(routerRedux.push('/data/report_template'));
    },
    *update({ payload }, { call, put }) {
      yield call(update, payload);
      yield put(routerRedux.push('/data/report_template'));
    },
    *queryProblemPage({ payload }, { call, put, select }) {
      const params = { ...payload };
      const response = yield call(queryProblemList, params);
      const ans = Array.isArray(response) ? response : []
      yield put({ type: 'setProblemPage', payload: { list: ans, total: ans.length } })
    },
  },

  reducers: {
    setCond(state, action) {
      return {
        ...state,
        cond: action.payload
      }
    },
    setPage(state, action) {
      return {
        ...state,
        list: {
          data: action.payload.list,
          dataCnt: action.payload.total
        }
      }
    },
    setDict(state, action) {
      return {
        ...state,
        dict: action.payload
      }
    },
    setInfo(state, action) {
      return {
        ...state,
        details: action.payload
      }
    },
    setProblemPage(state, action) {
      return {
        ...state,
        problemList: {
          data: action.payload.list,
          dataCnt: action.payload.total
        }
      }
    }
  }
}
